<template>
  <div>
    <link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.2/skins/default/aliplayer-min.css"/>
    <h4 class="lighter">
      <i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue"></i>
      <router-link to="/business/course" class="pink"> {{course.name}}:  &nbsp;</router-link>
      <i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue"></i>
      <router-link to="/business/chapter" class="pink"> {{chapter.name}} </router-link>
    </h4>
    <hr>
    <p>
      <button class="btn btn-white btn-default btn-round" @click="add()">
        <i class="ace-icon fa fa-edit"></i>
        新增
      </button>
      &nbsp;
      <button class="btn btn-white btn-default btn-round" @click="list(1)">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
    </p>

    <pagination ref="pagination" :list="list"></pagination>

    <table id="simple-table" class="table  table-bordered table-hover">
      <thead>
        <tr>
          <th>ID</th>
          <th>标题</th>
          <th>VOD</th>
          <th>时长</th>
          <th>收费</th>
          <th>顺序</th>
          <th>操作</th>
        </tr>
      </thead>

      <tbody>
        <tr v-for="section in sections"
          :key="section.id"
          :index="section.id">
          <td>{{section.id}}</td>
          <td>{{section.title}}</td>
          <td>{{section.vod}}</td>
          <td>{{section.time | formatSecond}}</td>
          <td>{{SECTION_CHARGE | optionKV(section.charge)}}</td>
          <td>{{section.sort}}</td>

          <td>
            <div class="btn-group">
              <button class="btn btn-xs btn-info" @click="play(section)">
                <i class="ace-icon fa fa-video-camera bigger-120"></i>
              </button>
              <button class="btn btn-xs btn-info" @click="edit(section)">
                <i class="ace-icon fa fa-pencil bigger-120"></i>
              </button>
              <button class="btn btn-xs btn-danger" @click="del(section.id)">
                <i class="ace-icon fa fa-trash-o bigger-120"></i>
              </button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 表单Modal -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">小节表单</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">标题</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="section.title">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">课程</label>
                <div class="col-sm-10">
                  <p class="form-control-static">{{course.name}}</p>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">大章</label>
                <div class="col-sm-10">
                  <p class="form-control-static">{{chapter.name}}</p>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">视频</label>
                <div class="col-sm-10">
                  <vod :text="'上传大视频'"
                        :input-id="'video-upload'"
                        :suffixs="['mp4']"
                        :use="FILE_USE.COURSE.key"
                        :after-upload="afterUpload"></vod>
                  <div v-show="section.video" class="row">
                    <div class="col-md-9">
                      <player ref="player" :player-id="'form-player-div'"></player>
                      <!-- controls="controls"是视频的菜单-->
                      <video id="video" :src="section.video" controls="controls" class="hidden"></video>
                    </div>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">时长</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="section.time" disabled>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">视频</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="section.video" disabled>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">VOD</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="section.vod" disabled>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">收费</label>
                <div class="col-sm-10">
                  <select v-model="section.charge" class="form-control">
                    <option v-for="o in SECTION_CHARGE" :value="o.key">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">顺序</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="section.sort">
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="save()">保存</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 视频播放Modal -->
    <modal-player ref="modalPlayer"></modal-player>

  </div>
</template>

<script>
  import Pagination from "../../components/pagination"
  import BigFile from  '../../components/big-file'
  import Vod from '../../components/vod'
  import Player from '../../components/player'
  import ModalPlayer from '../../components/modal-player'

  export default {
    name: "business-section",
    components: {Pagination, BigFile, Vod, Player, ModalPlayer},
    data() {
      return {
        section: {
          id: null,
          title: null,
          courseId: null,
          chapterId: null,
          video: null,
          time: null,
          charge: null,
          sort: null,
          createdAt: null,
          updatedAt: null,
          vod: null,
        },
        sections: [],
        //  引入枚举常量
        SECTION_CHARGE: SECTION_CHARGE,
        course: {},
        chapter: {},
        FILE_USE: FILE_USE
    }
    },
    mounted() {
      let _this = this
      //  因为section和chapter的路由跳转在admin.vue中被删除, 所以要在这里设置激活course的选中样式
      _this.$parent.activeSidebar('business-course-sidebar')

      let course = SessionStorage.get(SESSION_KEY_COURSE) || {}
      if (Tool.isEmpty(course)) {
        _this.$router.push('/welcome')
      }
      _this.course = course
      let chapter = SessionStorage.get(SESSION_KEY_CHAPTER) || {}
      if (Tool.isEmpty(chapter)) {
        _this.$router.push('/welcome')
      }
      _this.chapter = chapter
      _this.list(1)
    },
    methods: {
      /**
       * 获取小节（分页）
       * @param page
       */
      list(page) {
        let _this = this

        Loading.show()

        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/section/list', {
          page: page,
          size: _this.$refs.pagination.size,
          chapterId: _this.chapter.id
        }).then((resp) => {
          if (resp.data.success) {
            _this.sections = resp.data.content.list
            _this.$refs.pagination.render(page, resp.data.content.total)

            Loading.hide()
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 添加小节（显示模态框）
       */
      add() {
        let _this = this
        _this.section = {
          id: null,
          title: null,
          courseId: null,
          chapterId: null,
          video: null,
          time: null,
          charge: null,
          sort: null,
          createdAt: null,
          updatedAt: null,
          vod: null,
        }
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 编辑小节（显示模态框）
       */
      edit(section) {
        let _this = this
        //  Object.assign(target, source)方法用于对象的合并，将源对象（source）的所有可枚举属性，复制到目标对象（target)
        Object.assign(_this.section, section)
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 保存小节
       */
      save() {
        let _this = this

        _this.section.video = ''
        //  保存校验
        if (1 != 1
          || !Validator.require(_this.section.title, "标题")
          || !Validator.length(_this.section.title, "标题", 1, 50)
          || !Validator.length(_this.section.video, "视频", 1, 200)
        ) {
          return;
        }

        _this.section.courseId = _this.course.id
        _this.section.chapterId = _this.chapter.id

        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/section/save', _this.section).then((resp) => {
          if (resp.data.success) {
            //  关闭模态框
            $("#form-modal").modal('hide')
            //  刷新表格
            _this.list(1)
            Toast.success('保存成功！')
          } else {
            Toast.warning(resp.data.message)
          }
        })
      },

      /**
       * 删除小节（根据id）
       * @param id
       */
      del(id) {
        let _this = this
        Confirm.show('删除小节后不可恢复，是否确认删除？', () => {
          _this.$axios.delete(process.env.VUE_APP_SERVER + '/business/admin/section/delete/' + id).then((resp) => {
            if (resp.data.success) {
              //  刷新表格
              _this.list(1)
              Toast.success('删除成功！')
            }
          })
        })
      },

      /**
       * 上传文件组件的回调函数
       * @param resp
       */
      afterUpload(resp) {
        let _this = this
        let video = resp.data.content.path
        let vod = resp.data.content.vod
        _this.section.video = video
        _this.section.vod = vod
        _this.getTime()
        // _this.$refs.player.playUrl(video)
        _this.$refs.player.playVod(vod)
      },

      /**
       * 获取时长
       */
      getTime() {
        let _this = this
        setTimeout(() => {
          let ele = document.getElementById('video')
          _this.section.time = parseInt(ele.duration, 10) // duration 属性返回当前音频的长度，以秒计。
        }, 1000)
      },

      /**
       * 点击播放按钮, 播放视频
       * @param section
       */
      play(section) {
        let _this = this
        _this.$refs.modalPlayer.playVod(section.vod)
      }
    }
  }
</script>

<style scoped>

  video {
    width: 100%;
    height: auto;
    margin-top: 10px;
  }
</style>